//
//  DayReportViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/4/13.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class DayReportViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate {
    
    var segmentedControl: UISegmentedControl!
    var tableView: UITableView!
    
    var headArray = NSMutableArray()
    var reportArray = NSMutableArray()
    var listArray = NSMutableArray()//所有日报的列表
    
    //    var header1: UIView!
    var header2: UIView!
    
    var page = 1
    
    var mark = "1"
    var apiurl = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.title = "数据日报"
        
        InitHeaderView()
        InitViews()
    }
    
    /**
     初始化tableview的分隔
     */
    func InitHeaderView() {
        /*
        header1 = UIView.init(frame: CGRectMake(0, 0, screenW, 50))
        header1.backgroundColor = UIColor.init(hexString: "eeeeee", alpha: 1)

        let icon = UIImageView.init(frame: CGRectMake(10, 8, 27, 34))
        icon.layer.cornerRadius = 15
        icon.image = UIImage.init(named: "loginlogo")
        let title = UILabel.init(frame: CGRectMake(CGRectGetMaxX(icon.frame) + 10, 10, screenW - 60, 30))
        title.font = UIFont.boldSystemFontOfSize(16)
        title.textColor = UIColor.darkGrayColor()
        title.text = "昨日访问情况汇总"
        let line = UIView.init(frame: CGRectMake(40, 49, screenW, 1))
        line.backgroundColor = UIColor.init(hexString: "f0f0f0", alpha: 1)
        header1.addSubview(icon)
        header1.addSubview(title)
        header1.addSubview(line)
        
        */
        
        header2 = UIView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: 50))
        header2.backgroundColor = UIColor.init(hexString: "eeeeee", alpha: 1)
        let icon1 = UIImageView.init(frame: CGRect(x: 10, y: 8, width: 27, height: 34))
        icon1.layer.cornerRadius = 15
        icon1.image = logo
        icon1.contentMode = UIViewContentMode.scaleAspectFit
        let lable = UILabel.init(frame: CGRect(x: icon1.frame.maxX + 10, y: 10, width: screenW - 60, height: 30))
        lable.font = UIFont.boldSystemFont(ofSize: 16)
        lable.textColor = UIColor.darkGray
        lable.text = "今日数据汇总"
        header2.addSubview(icon1)
        header2.addSubview(lable)
    }
    /**
     初始化控件
     */
    func InitViews() {
        
        let array = ["今日日报","历史日报"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 30, y: 74, width: screenW - 60, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY+10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        //        tableView.tableFooterView = UIView()
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        //        tableView.separatorColor = UIColor.init(hexString: "f0f0f0", alpha: 1)
        //        tableView.separatorInset = UIEdgeInsetsMake(0, 40, 0, 0)
        self.view.addSubview(tableView)
        
        setUpRefresh()
    }
    
    func setUpRefresh() {
        if mark == "1" {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(DayReportViewController.refresh))
            tableView.footer = nil
        }else{
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(DayReportViewController.refresh))
            tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(DayReportViewController.loadMore))
        }
        
        tableView.header.beginRefreshing()
    }
    
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            setUpRefresh()
            break
        case 1:
            mark = "2"
            setUpRefresh()
            break
        default:
            break
        }
    }
    
    func refresh() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            
            var url = server + adminwebapppi
            if apiurl != "" {
                url = apiurl
            }
            if mark == "1" {
                let request = requestHeader + "20</t><sch>" + user.schid + "</sch></channel></rss>"
                var result = HttpUtils.httpPostUTF(url, with: request)
                result = result?.replacingOccurrences(of: "null", with: "\"\"")
                print(result!)
                
                let array = JSON(data: (result?.data(using: String.Encoding.utf8))!)
                if array.count != 0 {
                    for i in 0..<array.count {
                        headArray = NSMutableArray()
                        reportArray = NSMutableArray()
                        let dic = array[i]
                        
                        let userNum = dic["useNum"].stringValue//学校昨日使用人数（一个用户只计算一次）
//                        let useregcon = dic.objectForKey("useregcon")?.stringValue//学校的教师注册用户人数
//                        let usercon = dic.objectForKey("usercon")?.stringValue//学校的教师总人数
//                        let usernoregcon = dic.objectForKey("UserNoRegCon")?.stringValue//学校未注册教师用户
                        let classactcon = dic["classactcon"].intValue//学校当日班级活动发布的数量
                        let honorcon = dic["honorcon"].intValue//学校当日班级荣誉发布数量
                        let anncon = dic["AnnCon"].intValue//学校当日班级通知发布数量
                        let growthcon = dic["GrowthCon"].intValue//学校当日成长记录发布数量
                        let leavecon = dic["LeaveCon"].intValue//学校当日请假数量
                        let HomWorkCon = dic["HomWorkCon"].intValue //学校当日作业数量
                        let attCon = dic["attcon"].intValue//学校考勤数
                        let fwcon = dic["fwcon"].intValue//昨日访问量
                        let strper = dic["strper"].stringValue//活跃率
                        let fampracon = dic["fampracon"].stringValue//家长点赞数
                        let famrecon = dic["famRecon"].stringValue//家长评论数
                        let userpracon = dic["userpracon"].stringValue//所有点赞数
                        let userRecon = dic["userRecon"].stringValue//所有评论数
                        
//                        let count = classactcon! + honorcon! + anncon! + growthcon! + leavecon! + HomWorkCon!
                        
                        let users = "昨日访问量 \(fwcon)次 ，访问人数 \(userNum) 人"
                        
                        let allTeacher = "昨日活跃率 \(strper)%"
                        let signuser = "昨日家长点赞\(fampracon)次，评论\(famrecon)次"
                        let allComment = "昨日总点赞\(userpracon)次，评论\(userRecon)次"
                        //                    let allSend = "今日已发布数量\(count)个"
                        headArray.add(users)
                        headArray.add(allTeacher)
                        headArray.add(signuser)
                        headArray.add(allComment)
                        //                    headArray.addObject(allSend)
                        
                        
                        let classwork = "班级活动发布\(classactcon)次"
                        let classhornor = "班级荣誉发布\(honorcon)次"
                        let classnotice = "班级通知发布\(anncon)次"
                        let growth = "成长记录发布\(growthcon)次"
                        let leave = "今日请假次数\(leavecon)人"
                        let att = "今日考勤\(attCon)个班级"
                        let homework = "作业备忘发布\(HomWorkCon)次"
                        
                        reportArray.add(classwork)
                        reportArray.add(classnotice)
                        reportArray.add(classhornor)
                        reportArray.add(growth)
                        reportArray.add(leave)
                        reportArray.add(att)
                        reportArray.add(homework)
                    }
                }
                
            }else{
                page = 1
                let user = getUserPojo()
                let url = server + adminwebapppi
                let request = "\(requestHeader)30</t><sch>\(user.schid!)</sch><top>5</top><pagindex>\(page)</pagindex></channel></rss>"
                listArray = getData(url, request: request)
            }
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
        
        
        tableView.header.endRefreshing()
        
    }
    /**
     加载更多
     */
    func loadMore() {
        
        if (reachability?.isReachable())! {
            page += 1
            
            let user = getUserPojo()
            var url = server + adminwebapppi
            if apiurl != "" {
                url = apiurl
            }
            let request = "\(requestHeader)30</t><sch>\(user.schid!)</sch><top>5</top><pagindex>\(page)</pagindex></channel></rss>"
            listArray.addObjects(from: getData(url, request: request) as [AnyObject])
            
            //        tableView.reloadData()
            //        tableView.header.beginRefreshing()
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
        
        
        tableView.footer.endRefreshing()
    }
    
    //MARK: - table view delegate and data source
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            return 40
        }else{
            let dic = listArray[indexPath.row] as! JSON
            let useNum = dic["useNum"].stringValue //昨日使用人数
            let fwcon = dic["fwcon"].stringValue//昨日访问量
            let strper = dic["strper"].stringValue//活跃率
            let fampracon = dic["fampracon"].stringValue//家长点赞数
            let famrecon = dic["famrecon"].stringValue//家长评论数
            let userpracon = dic["userpracon"].stringValue//所有点赞数
            let userRecon = dic["userRecon"].stringValue//所有评论数
            
            let classactcon = dic["classactcon"].intValue//学校当日班级活动发布的数量
            let honorcon = dic["honorcon"].intValue//学校当日班级荣誉发布数量
            let anncon = dic["AnnCon"].intValue//学校当日班级通知发布数量
            let growthcon = dic["GrowthCon"].intValue//学校当日成长记录发布数量
            let leavecon = dic["LeaveCon"].intValue//学校当日请假数量
            let attCon = dic["attcon"].intValue//学校考勤数
            let HomWorkCon = dic["HomWorkCon"].intValue //学校当日作业数量
            
            let count = classactcon + honorcon + anncon + growthcon + leavecon + HomWorkCon + attCon
            
            let content = "访问量\(fwcon)次，访问人数\(useNum)人，活跃率\(strper)%，家长点赞\(fampracon)次，评论\(famrecon)次，总点赞\(userpracon)次，评论\(userRecon)次，总发布数量\(count)个。"
            return 150 + getLabelHeight(content, font: UIFont.boldSystemFont(ofSize: 14) , wigth: screenW - 110)+41
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if mark == "1" {
            return 50
        }else{
            return 0
        }
        
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if mark == "1" {
            return header2

        }else{
            return UIView()
        }
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if mark == "1" {
//            if section == 0 {
//                return headArray.count
//            }else{
            return reportArray.count
//            }
        }else{
            return listArray.count
        }
        
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "1" {
            let cellIdentifier = "DayReportTableViewCellIdentifier";
            if (indexPath as NSIndexPath).row < reportArray.count {
                let cell: DayReportTableViewCell = DayReportTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
                
                cell.selectionStyle = UITableViewCellSelectionStyle.none;
                
                cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
                let row = (indexPath as NSIndexPath).row
                let title = reportArray.object(at: row) as! String
                cell.title.text = title
                
                return cell
            }else {
                return UITableViewCell()
            }
        }else{
            let identifier = "DayReportListTableViewCellIdentifier"
            if (indexPath as NSIndexPath).row < listArray.count {
                let dic = listArray[indexPath.row] as! JSON
                let cell: DayReportListTableViewCell = DayReportListTableViewCell.init(dictionary: dic, reuseIdentifier: identifier)
                cell.selectionStyle = UITableViewCellSelectionStyle.none;
                return cell
            }else{
                return UITableViewCell()
            }
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if mark == "1" {
            //            if indexPath.section == 1 {
            switch (indexPath as NSIndexPath).row {
            case 0:
                let classwork = ClassWorkViewController()
                self.navigationController?.pushViewController(classwork, animated: true)
                break
            case 1:
                let notice = NoticeViewController()
                self.navigationController?.pushViewController(notice, animated: true)
                break
            case 2:
                let hornor = HonorViewController()
                self.navigationController?.pushViewController(hornor, animated: true)
                break
            case 3:
                let growth = GrowthViewController()
                self.navigationController?.pushViewController(growth, animated: true)
                break
            case 4:
                let leave = LeaveViewController()
                self.navigationController?.pushViewController(leave, animated: true)
                break
            case 5:
                let homework = HomeWorkViewController()
                self.navigationController?.pushViewController(homework, animated: true)
            default:
                break
            }
            
        }else{
            let dic = listArray[indexPath.row] as! JSON
            let dayReport = DayReportContentViewController()
            dayReport.dic = dic
            self.navigationController?.pushViewController(dayReport, animated: true)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
